package com.mysterymall.Service.Impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysterymall.Common.Comp.HttpStatus;
import com.mysterymall.Common.Comp.LocalCache;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.LogUtil;
import com.mysterymall.Common.Utils.Result;
import com.mysterymall.Mapper.*;
import com.mysterymall.Model.Dto.BlindBoxGroupDto;
import com.mysterymall.Model.Entity.*;
import com.mysterymall.Model.Vo.BlindBoxGroupVo;
import com.mysterymall.Model.Vo.BoxGroupGoodsShowVo;
import com.mysterymall.Model.Vo.BoxGroupGoodsVo;
import com.mysterymall.Model.Vo.UserGoodsVo;
import com.mysterymall.Service.BlindBoxGroupService;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @ClassName com.mysterymall.Service.Impl
 * @Description
 * @Author HuangWX
 * @Time 2023/11/16  11:50
 */
@Service
public class BlindBoxGroupServiceImpl implements BlindBoxGroupService {

    /**
     * 币种映射器
     */
    private final MoneyTypeMapper moneyTypeMapper;

    /**
     * 盲盒分组映射器
     */
    private final BlindBoxGroupMapper blindBoxGroupMapper;

    /**
     * 盲盒分组商品映射器
     */
    private final BoxGroupGoodsMapper boxGroupGoodsMapper;

    /**
     * 商品属性映射器
     */
    private final GoodsAttributeMapper goodsAttributeMapper;

    /**
     * 商品映射器
     */
    private final GoodsMapper goodsMapper;


    private final UserMapper userMapper;


    private final OrderInfoMapper orderInfoMapper;


    private final UserBlindBoxGroupMapper userBlindBoxGroupMapper;


    private final UserGoodsMapper userGoodsMapper;


    // 显示概率范围
    private final double[] legendaryRange = {8.00, 12.00};
    private final double[] epicRange = {20.00, 30.00};
    private final double[] rareRange = {30.00, 45.00};
    private final double[] advancedRange = {40.00, 60.00};


    /**
     * 构造器注入
     *
     * @param moneyTypeMapper      币种映射器
     * @param blindBoxGroupMapper  盲盒分组映射器
     * @param boxGroupGoodsMapper  盲盒分组商品映射器
     * @param goodsAttributeMapper 商品属性映射器
     * @param goodsMapper          商品映射器
     * @param userMapper           用户映射器
     */
    @Autowired
    public BlindBoxGroupServiceImpl(MoneyTypeMapper moneyTypeMapper, BlindBoxGroupMapper blindBoxGroupMapper,
                                    BoxGroupGoodsMapper boxGroupGoodsMapper, GoodsAttributeMapper goodsAttributeMapper,
                                    GoodsMapper goodsMapper, UserMapper userMapper, OrderInfoMapper orderInfoMapper,
                                    UserBlindBoxGroupMapper userBlindBoxGroupMapper, UserGoodsMapper userGoodsMapper) {
        this.moneyTypeMapper = moneyTypeMapper;
        this.blindBoxGroupMapper = blindBoxGroupMapper;
        this.boxGroupGoodsMapper = boxGroupGoodsMapper;
        this.goodsAttributeMapper = goodsAttributeMapper;
        this.goodsMapper = goodsMapper;
        this.userMapper = userMapper;
        this.orderInfoMapper = orderInfoMapper;
        this.userBlindBoxGroupMapper = userBlindBoxGroupMapper;
        this.userGoodsMapper = userGoodsMapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addBlindBoxGroup(BlindBoxGroupDto blindBoxGroupDto) {

        if (!StpUtil.hasPermission("blindBoxGroup:add:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        BlindBoxGroup blindBoxGroup = new BlindBoxGroup();

        // 盲盒分组金额
        blindBoxGroup.setGroupAmount(blindBoxGroupDto.getGroupAmount());

        // 盲盒名称
        blindBoxGroup.setGroupName(blindBoxGroupDto.getGroupName());

        //  盲盒分组图片
        StringBuilder groupImages = new StringBuilder();
        for (String groupImage :
                blindBoxGroupDto.getGroupImages()) {
            groupImages.append(groupImage).append("_");
        }
        blindBoxGroup.setGroupImages(groupImages.substring(0, groupImages.length() - 1));

        // 币种
        String moneyId = moneyTypeMapper.queryByCode("MYR").getId();
        blindBoxGroup.setMoneyCode(moneyId);

        // 状态
        blindBoxGroup.setGroupStatus(blindBoxGroupDto.getGrepStatus());

        // 连续盲盒价格
        blindBoxGroup.setGroupContinuousAmount(blindBoxGroupDto.getGroupContinuousAmount());

        // 概率
        StringBuilder goodsQuality = new StringBuilder();
        for (BigDecimal Chance :
                blindBoxGroupDto.getGoodsQualityChance()) {
            goodsQuality.append(Chance.doubleValue()).append("_");
        }
        blindBoxGroup.setGoodsQualityChance(goodsQuality.substring(0, goodsQuality.length() - 1));

        blindBoxGroupMapper.insert(blindBoxGroup);

        for (String groupGoods :
                blindBoxGroupDto.getGroupGoodsList()) {
            // 盲盒分组商品
            BoxGroupGoods boxGroupGoods = new BoxGroupGoods();
            // 组ID
            boxGroupGoods.setGroupId(blindBoxGroup.getId());
            // 商品ID
            boxGroupGoods.setGoodsId(groupGoods.split("_")[0]);
            // 币种
            boxGroupGoods.setMoneyCode(moneyId);
            // 属性ID
            boxGroupGoods.setGoodsAttributeId(groupGoods.split("_")[1]);
            // 概率
            boxGroupGoods.setGoodsQuality(Integer.valueOf(groupGoods.split("_")[2]));
            boxGroupGoodsMapper.insert(boxGroupGoods);
        }

        return Result.success("message.addSuccess");
    }

    @Override
    public Result getBlindBoxGroup(Integer currIndex, Integer pageSize) {

        if (!StpUtil.hasPermission("blindBoxGroup:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        Page<BlindBoxGroup> blindBoxGroupPage = new Page<>(currIndex, pageSize);

        blindBoxGroupMapper.selectPage(blindBoxGroupPage, null);

        return Result.success("message.querySuccess", blindBoxGroupPage);
    }

    @Override
    @Transactional
    public Result deleteBlindBoxGroup(String blindBoxGroupId) {

        if (!StpUtil.hasPermission("blindBoxGroup:delete:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        // 删除盲盒分组
        blindBoxGroupMapper.deleteById(blindBoxGroupId);

        // 删除盲盒分组商品
        QueryWrapper<BoxGroupGoods> boxGroupGoodsQueryWrapper = new QueryWrapper<>();

        boxGroupGoodsQueryWrapper.eq("group_id", blindBoxGroupId);

        boxGroupGoodsMapper.delete(boxGroupGoodsQueryWrapper);


        return Result.success("message.deleteSuccess");

    }

    @Override
    public Result getBlindBoxGroupMonocle(String blindBoxGroupId) {

        if (!StpUtil.hasPermission("blindBoxGroup:select:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        BlindBoxGroup blindBoxGroup = blindBoxGroupMapper.selectById(blindBoxGroupId);

        if (blindBoxGroup == null) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }


        QueryWrapper<BoxGroupGoods> boxGroupGoodsQueryWrapper = new QueryWrapper<>();

        boxGroupGoodsQueryWrapper.eq("group_id", blindBoxGroupId);

        List<BoxGroupGoods> BoxGroupGoods = boxGroupGoodsMapper.selectList(boxGroupGoodsQueryWrapper);


        List<BoxGroupGoodsVo> boxGroupGoodsVos = new ArrayList<>();

        for (BoxGroupGoods boxGroupGoods :
                BoxGroupGoods) {
            BoxGroupGoodsVo boxGroupGoodsVo = new BoxGroupGoodsVo();

            // 商品ID
            boxGroupGoodsVo.setGoodsId(boxGroupGoods.getGoodsId());

            // 组ID
            boxGroupGoodsVo.setGroupId(boxGroupGoods.getGroupId());

            // 商品
            Goods goods = goodsMapper.selectById(boxGroupGoods.getGoodsId());

            // 商品名称
            boxGroupGoodsVo.setGoodsName(goods.getGoodsName());


            // 品质等级
            boxGroupGoodsVo.setGoodsQuality(boxGroupGoods.getGoodsQuality());

            // 查询属性
            GoodsAttribute goodsAttribute = goodsAttributeMapper.selectById(boxGroupGoods.getGoodsAttributeId());

            // 属性名称
            boxGroupGoodsVo.setGoodsAttributeName(goodsAttribute.getAttributeName());

            // 属性ID
            boxGroupGoodsVo.setGoodsAttributeId(goodsAttribute.getId());

            // 属性价格
            boxGroupGoodsVo.setGoodsAttributeAmount(goodsAttribute.getGoodsAmount());

            boxGroupGoodsVos.add(boxGroupGoodsVo);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("blindBoxGroup", blindBoxGroup);
        map.put("boxGroupGoodsVos", boxGroupGoodsVos);

        return Result.success("message.querySuccess", map);
    }

    @Override
    @Transactional
    public Result updateBlindBoxGroup(BlindBoxGroupDto blindBoxGroupDto) {

        if (!StpUtil.hasPermission("blindBoxGroup:update:*")) {
            return new Result(HttpStatus.UNAUTHORIZED, "message.powerError");
        }

        BlindBoxGroup blindBoxGroup = blindBoxGroupMapper.selectById(blindBoxGroupDto.getGroupId());

        // 盲盒分组状态
        blindBoxGroup.setGroupStatus(blindBoxGroupDto.getGrepStatus());

        // 盲盒分组金额
        blindBoxGroup.setGroupAmount(blindBoxGroupDto.getGroupAmount());


        blindBoxGroup.setGroupContinuousAmount(blindBoxGroupDto.getGroupContinuousAmount());

        // 盲盒名称
        blindBoxGroup.setGroupName(blindBoxGroupDto.getGroupName());

        // 盲盒分组图片
        StringBuilder groupImages = new StringBuilder();
        for (String groupImage :
                blindBoxGroupDto.getGroupImages()) {
            groupImages.append(groupImage).append("_");
        }
        blindBoxGroup.setGroupImages(groupImages.substring(0, groupImages.length() - 1));

        // 概率
        StringBuilder goodsQuality = new StringBuilder();
        for (BigDecimal Chance :
                blindBoxGroupDto.getGoodsQualityChance()) {
            goodsQuality.append(Chance.doubleValue()).append("_");
        }
        blindBoxGroup.setGoodsQualityChance(goodsQuality.substring(0, goodsQuality.length() - 1));

        blindBoxGroupMapper.updateById(blindBoxGroup);

        QueryWrapper<BoxGroupGoods> boxGroupGoodsQueryWrapper = new QueryWrapper<>();

        boxGroupGoodsQueryWrapper.eq("group_id", blindBoxGroupDto.getGroupId());

        boxGroupGoodsMapper.delete(boxGroupGoodsQueryWrapper);

        for (String groupGoods :
                blindBoxGroupDto.getGroupGoodsList()) {
            // 盲盒分组商品
            BoxGroupGoods boxGroupGoods = new BoxGroupGoods();
            // 组ID
            boxGroupGoods.setGroupId(blindBoxGroup.getId());
            // 商品ID
            boxGroupGoods.setGoodsId(groupGoods.split("_")[0]);
            // 币种
            boxGroupGoods.setMoneyCode(blindBoxGroup.getMoneyCode());
            // 属性ID
            boxGroupGoods.setGoodsAttributeId(groupGoods.split("_")[1]);
            // 概率
            boxGroupGoods.setGoodsQuality(Integer.valueOf(groupGoods.split("_")[2]));
            boxGroupGoodsMapper.insert(boxGroupGoods);
        }

        return Result.success("message.updateSuccess");
    }

    @Override
    public Result getShowBoxGroup(HttpServletRequest request) {

        LambdaQueryWrapper<BlindBoxGroup> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BlindBoxGroup::getGroupStatus, 1);

        List<BlindBoxGroupVo> blindBoxGroups = new ArrayList<>();


        for (BlindBoxGroup blindBoxGroup :
                blindBoxGroupMapper.selectList(lambdaQueryWrapper)) {
            BlindBoxGroupVo blindBoxGroupVo = new BlindBoxGroupVo();
            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    blindBoxGroupVo.setGroupName(blindBoxGroup.getGroupName().split("_")[0]);
                    break;
                case "ms":
                    blindBoxGroupVo.setGroupName(blindBoxGroup.getGroupName().split("_")[1]);
                    break;
                case "en":
                    blindBoxGroupVo.setGroupName(blindBoxGroup.getGroupName().split("_")[2]);
                    break;
            }
            blindBoxGroupVo.setGroupId(blindBoxGroup.getId());
            blindBoxGroupVo.setGroupContinuousAmount(blindBoxGroup.getGroupContinuousAmount());
            blindBoxGroupVo.setGroupImageHome("/images/" + blindBoxGroup.getGroupImages().split("_")[0]);
            blindBoxGroupVo.setGroupImage("/images/" + blindBoxGroup.getGroupImages().split("_")[1]);
            blindBoxGroupVo.setGroupAmount(blindBoxGroup.getGroupAmount());
            blindBoxGroups.add(blindBoxGroupVo);
        }


        return Result.success("message.querySuccess", blindBoxGroups);
    }

    @Override
    public Result getBoxGroupGoods(String groupId) {

        BlindBoxGroup blindBoxGroup = blindBoxGroupMapper.selectById(groupId);

        if (blindBoxGroup == null) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }

        LambdaQueryWrapper<BoxGroupGoods> boxGroupGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();

        boxGroupGoodsLambdaQueryWrapper.eq(BoxGroupGoods::getGroupId, groupId);

        List<BoxGroupGoodsShowVo> boxGroupGoodsShowVos = new ArrayList<>();

        for (BoxGroupGoods boxGroupGoods :
                boxGroupGoodsMapper.selectList(boxGroupGoodsLambdaQueryWrapper)) {
            BoxGroupGoodsShowVo boxGroupGoodsShowVo = new BoxGroupGoodsShowVo();
            boxGroupGoodsShowVo.setGoodsId(boxGroupGoods.getGoodsId());
            boxGroupGoodsShowVo.setGoodsImage("/images/" + goodsMapper.selectById(boxGroupGoods.getGoodsId()).getGoodsImages().split("_")[0]);
            boxGroupGoodsShowVo.setGroupId(boxGroupGoods.getGroupId());
            boxGroupGoodsShowVos.add(boxGroupGoodsShowVo);
        }

        return Result.success("message.querySuccess", boxGroupGoodsShowVos);
    }

    @Override
    public Result getShowBlindBoxGroupMonocle(String blindBoxGroupId, HttpServletRequest request) {


        BlindBoxGroup blindBoxGroup = blindBoxGroupMapper.selectById(blindBoxGroupId);

        if (blindBoxGroup == null) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }

        switch ((String) request.getAttribute("Lang")) {
            case "zh":
                blindBoxGroup.setGroupName(blindBoxGroup.getGroupName().split("_")[0]);
                break;
            case "ms":
                blindBoxGroup.setGroupName(blindBoxGroup.getGroupName().split("_")[1]);
                break;
            case "en":
                blindBoxGroup.setGroupName(blindBoxGroup.getGroupName().split("_")[2]);
                break;
        }

        LambdaQueryWrapper<BoxGroupGoods> boxGroupGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();

        boxGroupGoodsLambdaQueryWrapper.eq(BoxGroupGoods::getGroupId, blindBoxGroupId);


        List<BoxGroupGoodsShowVo> boxGroupGoodsShowVos = new ArrayList<>();

        List<BoxGroupGoods> boxGroupGoodsList = boxGroupGoodsMapper.selectList(boxGroupGoodsLambdaQueryWrapper);


        for (int i = 0; i < 4; i++) {
            boxGroupGoodsShowVos.addAll(this.getBoxGroupGoodsList(boxGroupGoodsList, request).get(i));
        }

        Map<String, Object> map = new HashMap<>();


        Object o = LocalCache.CACHE.get(blindBoxGroup.getId());

        if (o != null) {
            blindBoxGroup.setGoodsQualityChance((String) o);
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            // 概率
            for (Double Chance :
                    this.generateProbabilities()) {
                stringBuilder.append(Chance).append("_");
            }
            String text = stringBuilder.substring(0, stringBuilder.length() - 1);

            LocalCache.CACHE.put(blindBoxGroup.getId(), text);
            blindBoxGroup.setGoodsQualityChance(text);
        }


        map.put("blindBoxGroup", blindBoxGroup);

        map.put("boxGroupGoodsShowVos", boxGroupGoodsShowVos);

        return Result.success("message.querySuccess", map);
    }

    @Override
    public Result getBlindBoxGroupGoods(String blindBoxGroupId, HttpServletRequest request) {

        BlindBoxGroup blindBoxGroup = blindBoxGroupMapper.selectById(blindBoxGroupId);

        if (blindBoxGroup == null) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }

        LambdaQueryWrapper<BoxGroupGoods> boxGroupGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();

        boxGroupGoodsLambdaQueryWrapper.eq(BoxGroupGoods::getGroupId, blindBoxGroupId);

        return Result.success("message.querySuccess", this.getBoxGroupGoodsList(boxGroupGoodsMapper.selectList(boxGroupGoodsLambdaQueryWrapper), request));
    }

    @Override
    public Result getMyBlindBoxGroup() {


        return null;
    }

    @Override
    public Result openBlindBoxTest(String id, Integer number, HttpServletRequest request) {


        List<BlindBoxGroup> blindBoxGroupList = blindBoxGroupMapper.selectList(new LambdaQueryWrapper<BlindBoxGroup>().eq(BlindBoxGroup::getGroupStatus, 1));

        if (blindBoxGroupList.size() == 0) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }

        BlindBoxGroup blindBoxGroup = blindBoxGroupList.get(0);

        List<BoxGroupGoods> boxGroupGoodsList = new ArrayList<>();

        // 开启盲盒
        for (int i = 0; i < number; i++) {
            boxGroupGoodsList.add(this.openBlindBoxControls(blindBoxGroup));
        }

        List<BoxGroupGoodsShowVo> boxGroupGoodsShowList = new ArrayList<>();

        this.getBoxGroupGoodsList(boxGroupGoodsList, request).forEach(boxGroupGoodsShowList::addAll);

        return Result.success("message.querySuccess", boxGroupGoodsShowList);
    }

    @Override
    @Transactional
    public Result openBlindBox(String id, Integer number, HttpServletRequest request) {


        User user = userMapper.selectById(StpUtil.getLoginId().toString());

        if (user == null) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }
        OrderInfo orderInfo = orderInfoMapper.selectById(id);

        if (orderInfo == null) {
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }

        if (!orderInfo.getCreateUser().equals(user.getId())) {
            // 封禁一天
            StpUtil.disable(user.getId(), 86400);
            LogUtil.error("尝试开盒的不属于自己的订单盲盒:  订单号: " + id + "\n" +
                    "账户ID: " + id + " 已被封禁一天 ");
            StpUtil.logout();
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }

        // 支付成功
        if (BaseEnum.Payment_Success.getCode().equals(orderInfo.getOrderStatus())) {

            LambdaQueryWrapper<UserBlindBoxGroup> userBlindBoxGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userBlindBoxGroupLambdaQueryWrapper.eq(UserBlindBoxGroup::getUserId, user.getId());
            userBlindBoxGroupLambdaQueryWrapper.eq(UserBlindBoxGroup::getOrderInfoId, orderInfo.getId());
            List<UserBlindBoxGroup> userBlindBoxGroupList = userBlindBoxGroupMapper.selectList(userBlindBoxGroupLambdaQueryWrapper);

            List<UserGoods> userGoodsList = new ArrayList<>();
            for (UserBlindBoxGroup userBlindBoxGroup : userBlindBoxGroupList) {
                // 未开启才能开启
                if (userBlindBoxGroup.getIsOpen().equals(BaseEnum.Not_Open.getCode())) {
                    userGoodsList.add(this.openBlindBoxControls(userBlindBoxGroup));
                    // 将用户盲盒改为已开启
                    userBlindBoxGroup.setIsOpen(BaseEnum.Yes_Open.getCode());
                    userBlindBoxGroupMapper.updateById(userBlindBoxGroup);
                } else {
                    // 封禁一天
                    StpUtil.disable(user.getId(), 86400);
                    LogUtil.error("尝试使用已开启的盲盒开盒:  订单号: " + id + "\n" +
                            "账户ID: " + id + " 已被封禁一天 ");
                    StpUtil.logout();
                    return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
                }
            }
            // 转换为用户盲盒
            for (UserGoods userGoods :
                    userGoodsList) {
                userGoods.setUserBlindBoxGroupId("");
                userGoods.setUserId(user.getId());
                userGoods.setOrderInfoId(orderInfo.getId());
                userGoods.setIsExchange(BaseEnum.Goods_Not_Exchange.getCode());
                userGoods.setDeleteIsStatus(BaseEnum.Not_Delete.getCode());
                // 改为归属到商品
                userGoods.setIsUserGoods(BaseEnum.Goods_Affiliation_User.getCode());
                userGoodsMapper.updateById(userGoods);
            }
            return new Result(HttpStatus.SUCCESS, "message.querySuccess", userGoodsList);

        } else {
            // 封禁一天
            StpUtil.disable(user.getId(), 86400);
            LogUtil.error("尝试使用未支付的订单号开盒:  订单号: " + id + "\n" +
                    "账户ID: " + id + " 已被封禁一天 ");
            StpUtil.logout();
            return new Result(HttpStatus.BAD_REQUEST, "message.queryError");
        }
    }

    @Override
    public Result getMyBoxList(String orderId, HttpServletRequest request) {

        LambdaQueryWrapper<UserBlindBoxGroup> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(UserBlindBoxGroup::getOrderInfoId, orderId);

        List<UserBlindBoxGroup> userBlindBoxGroupList = userBlindBoxGroupMapper.selectList(wrapper);


        List<UserGoods> userGoodsList1 = new ArrayList<>();
        for (UserBlindBoxGroup userBlindBoxGroup : userBlindBoxGroupList) {
            List<UserGoods> userGoodsList = new ArrayList<>();
            if (userBlindBoxGroup.getIsOpen().equals(BaseEnum.Not_Open.getCode())) {
                LambdaQueryWrapper<UserGoods> userGoodsWrapper = new LambdaQueryWrapper<>();
                userGoodsWrapper.eq(UserGoods::getUserBlindBoxGroupId, userBlindBoxGroup.getId());
                userGoodsList = userGoodsMapper.selectList(userGoodsWrapper);
                for (UserGoods userGoods : userGoodsList) {
                    switch ((String) request.getAttribute("Lang")) {
                        case "zh":
                            userGoods.setGoodsName(userGoods.getGoodsName().split("_")[0]);
                            break;
                        case "ms":
                            userGoods.setGoodsName(userGoods.getGoodsName().split("_")[1]);
                            break;
                        case "en":
                            userGoods.setGoodsName(userGoods.getGoodsName().split("_")[2]);
                            break;
                    }
                    userGoodsList1.add(userGoods);
                }
            }
        }
        return new Result(HttpStatus.SUCCESS, "message.querySuccess", userGoodsList1);
    }

    @Override
    public Result getMyBox(Integer current, Integer pageSize, HttpServletRequest request) {


        LambdaQueryWrapper<UserBlindBoxGroup> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(UserBlindBoxGroup::getUserId, StpUtil.getLoginId());
        wrapper.eq(UserBlindBoxGroup::getIsDelete, BaseEnum.Not_Delete.getCode());

        Page<UserBlindBoxGroup> userBlindBoxGroupPage = new Page<>(current, pageSize);

        List<UserBlindBoxGroup> userBlindBoxGroupList = new ArrayList<>();


        for (UserBlindBoxGroup userBlindBoxGroup :
                userBlindBoxGroupMapper.selectPage(userBlindBoxGroupPage, wrapper).getRecords()) {
            OrderInfo orderInfo = orderInfoMapper.selectById(userBlindBoxGroup.getOrderInfoId());
            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    userBlindBoxGroup.setGroupName(userBlindBoxGroup.getGroupName().split("_")[0]);
                    break;
                case "ms":
                    userBlindBoxGroup.setGroupName(userBlindBoxGroup.getGroupName().split("_")[1]);
                    break;
                case "en":
                    userBlindBoxGroup.setGroupName(userBlindBoxGroup.getGroupName().split("_")[2]);
                    break;
            }
            userBlindBoxGroupList.add(userBlindBoxGroup);
        }
        return new Result(HttpStatus.SUCCESS, "message.querySuccess", userBlindBoxGroupList);
    }


    public List<List<BoxGroupGoodsShowVo>> getBoxGroupGoodsList(List<BoxGroupGoods> boxGroupGoodsList, HttpServletRequest request) {

        List<List<BoxGroupGoodsShowVo>> boxGroupGoodsShowVos = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            boxGroupGoodsShowVos.add(new ArrayList<>());
        }
        for (BoxGroupGoods boxGroupGoods :
                boxGroupGoodsList) {
            BoxGroupGoodsShowVo boxGroupGoodsShowVo = new BoxGroupGoodsShowVo();
            boxGroupGoodsShowVo.setGoodsId(boxGroupGoods.getGoodsId());
            boxGroupGoodsShowVo.setGoodsImage("/images/" + goodsMapper.selectById(boxGroupGoods.getGoodsId()).getGoodsImages().split("_")[0]);
            boxGroupGoodsShowVo.setGroupId(boxGroupGoods.getGroupId());

            // 其他信息
            Goods goods = goodsMapper.selectById(boxGroupGoods.getGoodsId());

            // 属性信息
            GoodsAttribute goodsAttribute = goodsAttributeMapper.selectById(boxGroupGoods.getGoodsAttributeId());

            // 属性名称 和 商品名称
            switch ((String) request.getAttribute("Lang")) {
                case "zh":
                    boxGroupGoodsShowVo.setGoodsName(goods.getGoodsName().split("_")[0]);
                    boxGroupGoodsShowVo.setGoodsAttributeName(goodsAttribute.getAttributeName().split("&")[0]);
                    break;
                case "ms":
                    boxGroupGoodsShowVo.setGoodsName(goods.getGoodsName().split("_")[1]);
                    boxGroupGoodsShowVo.setGoodsAttributeName(goodsAttribute.getAttributeName().split("&")[1]);
                    break;
                case "en":
                    boxGroupGoodsShowVo.setGoodsName(goods.getGoodsName().split("_")[2]);
                    boxGroupGoodsShowVo.setGoodsAttributeName(goodsAttribute.getAttributeName().split("&")[2]);
                    break;
            }
            // 属性价格
            boxGroupGoodsShowVo.setGoodsAttributeAmount(goodsAttribute.getGoodsAmount());

            // 属性ID
            boxGroupGoodsShowVo.setGoodsAttributeId(goodsAttribute.getId());

            // 品质
            boxGroupGoodsShowVo.setGoodsQuality(boxGroupGoods.getGoodsQuality());

            switch (boxGroupGoods.getGoodsQuality()) {
                case 0:
                    boxGroupGoodsShowVos.get(0).add(boxGroupGoodsShowVo);
                    break;
                case 1:
                    boxGroupGoodsShowVos.get(1).add(boxGroupGoodsShowVo);
                    break;
                case 2:
                    boxGroupGoodsShowVos.get(2).add(boxGroupGoodsShowVo);
                    break;
                case 3:
                    boxGroupGoodsShowVos.get(3).add(boxGroupGoodsShowVo);
                    break;
            }
        }

        return boxGroupGoodsShowVos;
    }

    BoxGroupGoods openBlindBoxControls(BlindBoxGroup blindBoxGroup) {


        // 盲盒抽奖概率
        List<Double> goodsQualityChance = new ArrayList<>();
        for (String quality : blindBoxGroup.getGoodsQualityChance().split("_")) {
            goodsQualityChance.add(new BigDecimal(quality).divide(new BigDecimal(100)).doubleValue());
        }

        // 自定义概率
        goodsQualityChance =  new  ArrayList<Double>() {{
            add(0.6);
            add(0.3);
            add(0.1);
            add((double) 0);
        }};

        // 生成一个随机数
        double random = Math.random();

        // 判断随机数在哪个区间
        int index = -1;


        // 判断在那个区间，不使用for循环, 且将goodsQualityChance.get(0)放在接近1的位置
        if (random >= goodsQualityChance.get(1) + goodsQualityChance.get(2) + goodsQualityChance.get(3) && random < goodsQualityChance.get(0) + goodsQualityChance.get(1) + goodsQualityChance.get(2) + goodsQualityChance.get(3)) {
            index = 0;
        } else if (random >= goodsQualityChance.get(2) + goodsQualityChance.get(3) && random < goodsQualityChance.get(1) + goodsQualityChance.get(2) + goodsQualityChance.get(3)) {
            index = 1;
        } else if (random >= goodsQualityChance.get(3) && random < goodsQualityChance.get(2) + goodsQualityChance.get(3)) {
            index = 2;
        } else if (random < goodsQualityChance.get(3)) {
            index = 3;
        }


        LogUtil.info("盲盒分组id:" + blindBoxGroup.getId() + " 生成的随机数:" + random + " 生成的品质:" + index);

        // 根据品质获取商品
        LambdaQueryWrapper<BoxGroupGoods> boxGroupGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        boxGroupGoodsLambdaQueryWrapper.eq(BoxGroupGoods::getGroupId, blindBoxGroup.getId());
        boxGroupGoodsLambdaQueryWrapper.eq(BoxGroupGoods::getGoodsQuality, index);

        // 获取商品
        List<BoxGroupGoods> boxGroupGoods = boxGroupGoodsMapper.selectList(boxGroupGoodsLambdaQueryWrapper);


        // 产生一个 boxGroupGoods 长度的随机数
        int randomIndex = (int) (Math.random() * boxGroupGoods.size());


        return boxGroupGoods.get(randomIndex);
    }


    UserGoods openBlindBoxControls(UserBlindBoxGroup blindBoxGroup) {


        // 盲盒抽奖概率
        List<Double> goodsQualityChance = new ArrayList<>();
        for (String quality : blindBoxGroup.getGoodsQualityChance().split("_")) {
            goodsQualityChance.add(new BigDecimal(quality).divide(new BigDecimal(100)).doubleValue());
        }

        // 生成一个随机数
        double random = Math.random();

        // 判断随机数在哪个区间
        int index = -1;


        // 判断在那个区间，不使用for循环, 且将goodsQualityChance.get(0)放在接近1的位置
        if (random >= goodsQualityChance.get(1) + goodsQualityChance.get(2) + goodsQualityChance.get(3) && random < goodsQualityChance.get(0) + goodsQualityChance.get(1) + goodsQualityChance.get(2) + goodsQualityChance.get(3)) {
            index = 0;
        } else if (random >= goodsQualityChance.get(2) + goodsQualityChance.get(3) && random < goodsQualityChance.get(1) + goodsQualityChance.get(2) + goodsQualityChance.get(3)) {
            index = 1;
        } else if (random >= goodsQualityChance.get(3) && random < goodsQualityChance.get(2) + goodsQualityChance.get(3)) {
            index = 2;
        } else if (random < goodsQualityChance.get(3)) {
            index = 3;
        }


        LogUtil.info("盲盒分组id:" + blindBoxGroup.getId() + " 生成的随机数:" + random + " 生成的品质:" + index);

        // 根据品质获取商品
        LambdaQueryWrapper<UserGoods> boxGroupGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        boxGroupGoodsLambdaQueryWrapper.eq(UserGoods::getUserBlindBoxGroupId, blindBoxGroup.getId());
        boxGroupGoodsLambdaQueryWrapper.eq(UserGoods::getGoodsQuality, index);
        // 获取商品
        List<UserGoods> boxGroupGoods = userGoodsMapper.selectList(boxGroupGoodsLambdaQueryWrapper);


        // 产生一个 boxGroupGoods 长度的随机数
        int randomIndex = (int) (Math.random() * boxGroupGoods.size());


        return boxGroupGoods.get(randomIndex);
    }

    private List<Double> generateProbabilities() {
        // 定义概率范围


        // 生成随机概率
        double legendaryProbability = getRandomDoubleInclusive(legendaryRange[0], legendaryRange[1]);
        double epicProbability = getRandomDoubleInclusive(epicRange[0], epicRange[1]);
        double rareProbability = getRandomDoubleInclusive(rareRange[0], rareRange[1]);
        double advancedProbability = getRandomDoubleInclusive(advancedRange[0], advancedRange[1]);

        // 计算总和
        double totalProbability = legendaryProbability + epicProbability + rareProbability + advancedProbability;

        // 调整概率，使总和为100%
        double adjustmentFactor = 100.0 / totalProbability;
        double adjustedLegendary = legendaryProbability * adjustmentFactor;
        double adjustedEpic = epicProbability * adjustmentFactor;
        double adjustedRare = rareProbability * adjustmentFactor;
        double adjustedAdvanced = advancedProbability * adjustmentFactor;

        // 格式化概率，保留两位小数
        DecimalFormat df = new DecimalFormat("#.##");
        adjustedLegendary = Double.parseDouble(df.format(adjustedLegendary));
        adjustedEpic = Double.parseDouble(df.format(adjustedEpic));
        adjustedRare = Double.parseDouble(df.format(adjustedRare));
        adjustedAdvanced = Double.parseDouble(df.format(adjustedAdvanced));

        // 调整后的概率
        List<Double> adjustedProbabilities = new ArrayList<>();
        adjustedProbabilities.add(adjustedLegendary);
        adjustedProbabilities.add(adjustedEpic);
        adjustedProbabilities.add(adjustedRare);
        adjustedProbabilities.add(adjustedAdvanced);
        return adjustedProbabilities;
    }

    // 生成指定范围内的随机浮点数（包括边界）
    private double getRandomDoubleInclusive(double min, double max) {
        Random random = new Random();
        return min + (max - min) * random.nextDouble();
    }
}
